package com.stand.hardcode.controller;

import javax.servlet.*;
import javax.servlet.http.*;

import java.util.Date;
import java.text.*;

import java.io.*;

import com.stand.hardcode.entity.*;
import com.stand.hardcode.manager.*;
import com.stand.hardcode.util.RequestAttributes;

public class CreateItemServlet extends HttpServlet {
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (UserManager.IsLoggedIn(request)) {
			try {
			StandUser user = (StandUser)request.getSession().getAttribute(RequestAttributes.CURRENT_USER);
			String itemName = request.getParameter("itemName");
			String itemDescription = request.getParameter("itemDescription");
			double itemPrice = Double.parseDouble(request.getParameter("itemPrice"));
			int itemQuantity = Integer.parseInt(request.getParameter("itemQuantity"));
			String expiryDateStr = request.getParameter("expiryDateStr");
			
			SimpleDateFormat sdf = new SimpleDateFormat();
			Date expiryDate = sdf.parse(expiryDateStr);
			
			ItemManager itemManager = new ItemManager();
			itemManager.createItem(itemName, itemDescription, itemPrice, 1, "", itemQuantity, expiryDate, user.getEmail());
			
			request.setAttribute("message", "Item successfully created");
			
			getServletContext().getRequestDispatcher("/create_item_form.jsp").forward(request, response);
			}
			catch (Exception e) {
				e.printStackTrace();
				request.setAttribute("message", "Item was not created due to some errors");
				getServletContext().getRequestDispatcher("/create_item_form.jsp").forward(request, response);
			}
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (UserManager.IsLoggedIn(request)) {
			getServletContext().getRequestDispatcher("/create_item_form.jsp").forward(request, response);
		}
	}
}
